package com.bjpowernode.web.controller;

import com.bjpowernode.common.P2PConstants;
import com.bjpowernode.common.P2PKey;
import com.bjpowernode.model.FinanceAccount;
import com.bjpowernode.model.LoanInfo;
import com.bjpowernode.model.User;
import com.bjpowernode.model.ext.BidLoanInfo;
import com.bjpowernode.service.BidInfoService;
import com.bjpowernode.service.FinanceAccountService;
import com.bjpowernode.service.LoanInfoService;
import com.bjpowernode.vo.PageVo;
import com.bjpowernode.vo.TopBean;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;


@Controller
public class LoanInfoController {

    @DubboReference(interfaceClass = LoanInfoService.class)
    private LoanInfoService loanInfoService;

    @DubboReference(interfaceClass = BidInfoService.class)
    private BidInfoService bidInfoService;

    @DubboReference(interfaceClass = FinanceAccountService.class)
    private FinanceAccountService financeAccountService;

    @Resource
    private RedisTemplate redisTemplate;

    //分页查询产品
    @GetMapping("/loan/loan")
    public String loanPage(@RequestParam("ptype") Integer productType,
                           //可以不存在，不存在时默认值为1
                           @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                           @RequestParam(value = "pageSize", required = false, defaultValue = "9") Integer pageSize,
                           Model model) {

        PageVo pageVo = new PageVo();

        List<LoanInfo> loanInfoList = new ArrayList<>();//实例化了，不存在null的情况。只存在0和>0的情况
        //参数检查
        if (checkProductType(productType)) {
            pageNo = (pageNo < 1 || pageNo > 100) ? 1 : pageNo;
            pageSize = (pageSize < 1 || pageSize > 100) ? 9 : pageSize;
            //查询产品列表
            loanInfoList = loanInfoService.queryLoanPageByProductType(productType, pageNo, pageSize);

            //计算总记录数
            int recordNums = loanInfoService.queryRecordNumByProductType(productType);

            //PageVo
            pageVo.setPageNo(pageNo);
            pageVo.setPageSize(pageSize);
            pageVo.setTotalRecord(recordNums);

        }
        model.addAttribute("ptype",productType);
        model.addAttribute("pageVo", pageVo);
        model.addAttribute("loanInfoList", loanInfoList);

        //@TODO 投资排行榜，在投资功能完成后实现这里
        //reverseRangeWithScores()将zset按照分数反向排序，由高往低排。
        Set<ZSetOperations.TypedTuple<String>> set =redisTemplate.opsForZSet().reverseRangeWithScores(P2PKey.BID_TOP_LIST,0,5);

        List<TopBean> topList=new ArrayList<>();
        set.forEach(c->{
            TopBean bean =new TopBean();
            bean.setPhone(c.getValue());
            bean.setMoney(c.getScore());
            topList.add(bean);
        });

        model.addAttribute("topList",topList);
        return "loan";
    }

    private boolean checkProductType(Integer paramProductType) {
        boolean result = false;//没有通过
        if (paramProductType == 0 || paramProductType == 1 || paramProductType == 2) {
            result = true;
        }
        return result;
    }

    //单个的产品详情
    @GetMapping("/loan/loanInfo")
    public String loanInfo(@RequestParam("loanId") Integer loanId,
                           Model model,
                           HttpSession session){
        BigDecimal availableMoney =new BigDecimal("0");
        LoanInfo loanInfo = null;
        List<BidLoanInfo> bidLoanInfoList = new ArrayList<>();//实例化，永远不会是null
        if (loanId>0){
            //做查询
            loanInfo=loanInfoService.queryLoanInfoByIb(loanId);
            //投资记录
            bidLoanInfoList = bidInfoService.queryRecentlyBidRecordByLoanId(loanId);
        }

        //获取FianceAccount的金额
        User user = (User) session.getAttribute(P2PConstants.SESSION_USER);
        if (user!=null){
            //查询金额
            FinanceAccount financeAccount=financeAccountService.queryAccountByUid(user.getId());
            if (financeAccount!=null){
                availableMoney =financeAccount.getAvailableMoney();
            }
        }
        //添加数据到model
        model.addAttribute("loanInfo",loanInfo);
        model.addAttribute("bidLoanInfoList",bidLoanInfoList);
        model.addAttribute("accountMoney",availableMoney);
        return "loanInfo";
    }
}
